/*
 * Author: yezi
 * E-mail: okye328@gmail.com
 * Create time: Dec 31, 2012 9:47:20 PM
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
package com.kanbox.linux.operation;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.message.BasicNameValuePair;

import com.alibaba.fastjson.JSONObject;
import com.kanbox.linux.fs.FolderHash;
import com.kanbox.linux.fs.INode;
import com.kanbox.linux.fs.MountPointManager;
import com.kanbox.linux.operation.http.HttpExecutor;
import com.kanbox.linux.operation.http.RequestFactory;
import com.kanbox.linux.operation.http.RequestFactory.RequestType;
import com.kanbox.linux.token.TokenManager;

public class FileList {

	/**
	 * 
	 * @param path
	 *            the related path
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public List<INode> list(String path) throws FileNotFoundException {
		if (path == null) {
			path = "/";
		}

		String accessToken = TokenManager.getAccessToken();

		FolderHash folderHash = new FolderHash(path);
		String savedHash = folderHash.getHash();

		HttpUriRequest httpRequest = null;
		if (savedHash == null || savedHash.equals("")) {
			httpRequest = RequestFactory.buildHTTPRequest(RequestFactory.LIST,
					path, RequestType.GET, accessToken);
		} else {
			httpRequest = RequestFactory.buildHTTPRequest(RequestFactory.LIST,
					path, RequestType.GET, accessToken, new BasicNameValuePair(
							"hash", savedHash));
		}
		JSONObject response = HttpExecutor.executeForJSON(httpRequest);
		if (response.getString("status").equalsIgnoreCase("error")) {
			// If the list is used to check the local directory, maybe the
			// exception will get
			throw new FileNotFoundException("Error path:" + path
					+ " Error info:" + response.toJSONString()
					+ " The path does not exist, maybe it is a file?");
		} else if (response.getString("status").equalsIgnoreCase("ok")) {
			folderHash = new FolderHash(path, response.getLong("hash")
					.toString(), response.getJSONArray("contents")
					.toJSONString());
			// Auto saved
		} else if (response.getString("status").equalsIgnoreCase("nochange")) {
			// Nothing todo
		}

		List<INode> res = folderHash.getChildNodes();
		for (INode iNode : res) {
			if (iNode.isFolder()) {
				new File(MountPointManager.remoteToLocalDataPath(iNode
						.getFullPath())).mkdirs();
			}
		}

		return res;
	}

	public List<INode> listRecurse(String path) throws FileNotFoundException {
		LinkedList<INode> todolist = new LinkedList<INode>();
		LinkedList<INode> res = new LinkedList<INode>();
		List<INode> temp = list(path);
		todolist.addAll(temp);
		res.addAll(temp);
		while (todolist.size() > 0) {
			INode todo = todolist.removeFirst();
			if (!todo.isFolder())
				continue;
			List<INode> tmpIn = list(todo.getFullPath());
			todolist.addAll(tmpIn);
			res.addAll(tmpIn);
		}
		//
		// for (INode iNode : list) {
		// if (iNode.isFolder()) {
		// tempList.addAll(listRecurse(iNode.getFullPath()));
		// }
		// }
		// list.addAll(tempList);
		return res;
	}

}
